package com.xingchi.tornado.security.filter;

import com.xingchi.tornado.security.context.RequestContext;
import com.xingchi.tornado.security.model.UnifiedAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 填充请求上下文对象过滤器
 *
 * @author xingchi
 * @date 2025/3/15 17:44
 */
public class FullRequestContextFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            SecurityContext context = SecurityContextHolder.getContext();
            UnifiedAuthenticationToken authentication = (UnifiedAuthenticationToken) context.getAuthentication();
            if (authentication != null) {
                HttpServletRequest request = (HttpServletRequest) servletRequest;
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                RequestContext.init(request, response, servletRequest.getServletContext());
            }
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            RequestContext.clear();
        }
    }
}
